package com.wys.read.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.wys.read.dao.ArticleCategoryDao;
import com.wys.read.dao.ArticleDao;
import com.wys.read.dao.CategoryDao;
import com.wys.read.entity.Article;
import com.wys.read.entity.ArticleCategory;
import com.wys.read.entity.Category;
import com.wys.read.vo.CategoryVO;
import com.wys.read.vo.TitleVO;
import lombok.extern.slf4j.Slf4j;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.wys.read.utils.Constant.CATEGORY_DEFAULT;

/**
 * @author wys
 * created in 23:23 2019/1/4
 */
@Slf4j
@Service
public class ArticleService {

    @Autowired
    private ArticleDao articleDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private ArticleCategoryDao articleCategoryDao;

    /**
     * 添加文章
     * 1.添加文章  判断文章的分类 空 就添加为other默认
     * 2.添加文章的标签->添加article label
     * 3.添加了文章才开始添加分类 如果添加文章的时候没有分类，
     *   就添加到默认的分类中
     *
     * @param article
     * @return
     */
    @Transactional
    public Boolean articleAdd(Article article) {

        LambdaQuery<Article> articleLambdaQuery = articleDao.createLambdaQuery();

        long count = articleLambdaQuery.andEq(Article::getTitle, article.getTitle()).count();
        if (count == 1) {
            return Boolean.FALSE;
        }
        LambdaQuery<Category> categoryLambdaQuery = categoryDao.createLambdaQuery();

        if (StrUtil.isBlank(article.getCategory())) {
            article.setCategory(CATEGORY_DEFAULT);
        }
        try {
            articleDao.insert(article);

            Article articleCate = articleLambdaQuery.andEq(Article::getTitle, article.getTitle()).single();
            Category category = categoryLambdaQuery.andEq(Category::getCategory, article.getCategory()).single();
            if (ObjectUtil.isNull(category)) {
                category.setCategory(articleCate.getCategory());
                categoryDao.insert(category);
            } else {
                categoryDao.insert(Category.builder()
                        .category(articleCate.getCategory())
                        .count((int) categoryLambdaQuery.andEq(Category::getCategory,
                                articleCate.getCategory()).count())
                        .build());
            }
            ArticleCategory articleCategory = ArticleCategory.builder()
                    .articleId(articleCate.getId())
                    .categoryId(categoryLambdaQuery.andEq(Category::getCategory,
                            articleCate.getCategory()).single().getId())
                    .build();
            articleCategoryDao.insert(articleCategory);
        } catch (Exception e) {
            log.info("数据库错误 {}", e.getMessage());

        }

        return Boolean.TRUE;
    }

    /**
     * 删除文章
     *
     * @param articleId 文章标题
     * @return
     */
    public int articleDelete(Integer articleId, String category) {

        if (ObjectUtil.isNull(articleId)) {

        }
        int result = 0;
        LambdaQuery<Article> articleLambdaQuery = articleDao.createLambdaQuery();
        long count = articleLambdaQuery.andEq(Article::getId, articleId).count();
        if (count == 1) {
            return result;
        }
        try {
            result = articleDao.deleteById(articleId);
            result = articleCategoryDao.deleteByArticleId(articleId);
            Category categoryDb = categoryDao
                    .createLambdaQuery().andEq(Category::getCategory, category)
                    .single();
            // 有这个分类  分类的数量就减1
            if (ObjectUtil.isNotNull(categoryDb)) {
                categoryDb.setCount(categoryDb.getCount() - 1);
                categoryDao.updateById(categoryDb);
            }
        }catch (Exception e) {
            log.info("数据库错误 {}", e.getMessage());

        }

        return result;
    }

    /**
     * 更新文章
     * @param article 文章
     * @return
     */
    public int articleUpdate(Article article) {

        if (ObjectUtil.isNull(article)) {

        }

        int result = 0;

        long count = articleDao.createLambdaQuery().andEq(Article::getAid, article.getAid()).count();
        if (count == 0) {
            return result;
        }
        try {
            result = articleDao.updateById(article);
        }catch (Exception e) {

        }

        return result;
    }

    /**
     * 通过文章ID获得一篇文章
     * @param articleId 文章ID
     * @return
     */
    public Article getArticle(Integer articleId) {
        if (ObjectUtil.isNull(articleId)) {

        }
        Article article = articleDao.createLambdaQuery().andEq(Article::getId, articleId).single();
        return article;
    }

    /**
     * 分页获取文章
     * @param page 页数
     * @param limit 一页数量
     * @return
     */
    public PageQuery<Article> getPageArticle(int page, int limit) {
        PageQuery<Article> pageQuery = articleDao.createLambdaQuery().page(page, limit);
        return pageQuery;
    }

    /**
     * 获取最新的5篇文章
     * @return
     */
    public List<Article> getNewArticles() {
        List<Article> articles = articleDao.getNewArticles();
        return articles;
    }

    /**
     * 获取文章  文章查看  通过分类类型
     * @param category  分类类型
     * @return 文章
     */
    public List<Article> getArticles(String category) {

        List<Article> articles = new ArrayList<>();
        // 如果为空,就找默认的一页10篇
        if (StrUtil.isBlank(category)) {
            articles = articleDao.createLambdaQuery().andEq(Article::getCategory, CATEGORY_DEFAULT).select();
        }

        articles = articleDao.createLambdaQuery().andEq(Article::getCategory, category).select();

        return articles;
    }

    /**
     * 最新更新
     * @return
     */
    public List<TitleVO> getUpdateArticles() {

        List<TitleVO> updateArticles = articleDao.getUpdateArticles();
        return updateArticles;
    }

    /**
     * 分类
     * @return
     */
    public List<CategoryVO> getCategory() {

        List<CategoryVO> voList = categoryDao.getCategory();

        return voList;
    }

    // todo
//    /**
//     * 获取文章的标签
//     * @return 标签数组
//     */
//    public List<LabelVO> getLable() {
//
//
//
//        return ResultUtil.success();
//    }

}
